
$(function () {
    function renderList() {
        $.ajax({
            url:'http://localhost:8080/api/v1/admin/category/list',
            headers:{
                Authorization:localStorage.getItem('token')
            },
            success(res) {
                if (res.code == 200) {
                    console.log(res);
                    const list = res.data
                    $('tbody').html(template('listTpl',{list}))
                } else {
                    console.log(res.msg);
                }
            }
        })
    }
    renderList()
    $('#save').click(function () {
        const name = $('[name="name"]').val().trim()
        const slug = $('[name="slug"]').val().trim()
        if (!name.length || !slug.length) return
        $.ajax({
            url:'http://localhost:8080/api/v1/admin/category/add',
            type:'post',
            headers:{
                Authorization:localStorage.getItem('token')
            },
            data:{name,slug},
            success(res) {
                if (res.code == 200) {
                    $('[name="name"]').val('')
                    $('[name="slug"]').val('')
                    $('#myModal').modal('hide')
                    renderList()
                }else {
                    console.log(res.msg);
                }
                
            }
        })
    })
    let value = ''
    $('tbody').on('click','.edit',function () {
        // console.log($(this).parents('tr').data('id'));
        $('#editModal').modal('show')
        value = $(this).parents('tr').data('value')
        $('#editModal #name').val(value.name)
        $('#editModal #slug').val(value.slug)
    })
    $('#editModal #editSave').click(function () {
        console.log(value);
        let id = value.id - 0
        let name = $('#editModal #name').val()
        let slug = $('#editModal #slug').val()
        $('#editModal').modal('hide')
        $.ajax({
            url:'http://localhost:8080/api/v1/admin/category/edit',
            type:'post',
            headers:{
                Authorization:localStorage.getItem('token')
            },
            data:{id,name,slug},
            success(res) {
                if (res.code == 200) {
                    console.log(res.msg);
                    renderList()
                } else {
                    console.log(res.msg);
                }
            }
        })
    })
    $('tbody').on('click','.delete',function () {
        const id = $(this).parents('tr').data('value').id
        $.ajax({
            url:'http://localhost:8080/api/v1/admin/category/delete',
            type:'post',
            data:{id},
            headers:{
                Authorization:localStorage.getItem('token')
            },
            success(res) {
                console.log(res.msg);
                renderList()
            }
        })
    })
})